package org.abettor.nookinfo.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.modal.PhotoDailyItem;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class PhotoDailyList extends ListActivity {
	private YoumiManager youmi = new YoumiManager(this);
	private static final int ICON_WIDTH = 64;
	private static final int ICON_HEIGHT = 64;
	private float scaleRatio;
	public static final String PHOTO_CATEGORY_ID = "PHOTO_CATEGORY_ID";// 参数,所属类别的ID
	public static final String PHOTO_CATEGORY_NAME = "PHOTO_CATEGORY_NAME";// 参数,所属类别的名称
	private static final int REFRESHED = 1;// 菜单更新已完成事件
	private static final int FAILED = 2;// 菜单更新失败时间
	private int category;
	private String categoryName;
	private int page = 1;
	private List<PhotoDailyItem> dailyItems = new ArrayList<PhotoDailyItem>();
	private Map<String, Bitmap> bitmapMap = new HashMap<String, Bitmap>();// 更新图片的bitmap
	private ProgressDialog progressDialog = null;// 进度条对话框
	private Worker worker = null;// 网络访问线程
	private ImageListAdapter listAdapter;// 更新列表的程序
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == REFRESHED) {
				listAdapter.notifyDataSetChanged();
				// 启动更新图片的线程
				Thread thread = new Thread(new PhotoDailyUpdateThread());
				thread.start();
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 25) {
					youmi.showYoumi(YoumiManager.Position.top, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			} else if (msg.what == FAILED) {
				Builder builder = new Builder(PhotoDailyList.this);
				builder.setTitle(R.string.photo_daily_list_fail_title);
				builder.setMessage(R.string.photo_daily_list_fail_content);
				builder.setPositiveButton(
						R.string.photo_daily_list_fail_btn_ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(
									DialogInterface dialoginterface, int i) {
								dialoginterface.dismiss();
							}
						});
				builder.show();
			}
			super.handleMessage(msg);
		}
	};
	// 更新图片的操作
	private Handler drawImageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			listAdapter.notifyDataSetChanged();
		}
	};

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		LinearLayout layoutH = (LinearLayout) v;
		LinearLayout layoutV = (LinearLayout) layoutH.getChildAt(1);
		TextView text = (TextView) layoutV.getChildAt(0);
		String content = (String) text.getText();
		String date = content.substring(content.length() - 8, content.length());
		date = date.replaceAll("-", "/");

		Intent in = new Intent();
		in.setClass(this, PhotoThumbnail.class);
		Bundle extras = new Bundle();
		extras.putInt(PhotoThumbnail.PHOTO_DAILY_ID, (int) id);
		extras.putString(PhotoThumbnail.PHOTO_DAILY_NAME, date);
		extras.putString(PHOTO_CATEGORY_NAME, categoryName);
		extras.putInt(PHOTO_CATEGORY_ID, category);
		in.putExtras(extras);
		startActivity(in);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.photo_daily_list);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		scaleRatio = dm.density;

		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		category = extras.getInt(PHOTO_CATEGORY_ID);
		categoryName = extras.getString(PHOTO_CATEGORY_NAME);
		String label = getString(R.string.photo_daily_list_label);
		label = label.replace("REPL", categoryName);
		setTitle(label);
		onUpdateClicked(null);
		listAdapter = new ImageListAdapter();
		this.setListAdapter(listAdapter);
		// 滚动的监听器
		// this.getListView().setOnScrollListener(this);
	}

	/**
	 * “更新”按钮事件方法
	 * 
	 * @param v
	 */
	public void onUpdateClicked(View v) {
		// 如果确定点击的是更新按钮，就删除已保存的图片文件
		if (v != null && v.getId() == R.id.photoDailyListUpdate) {
			for (PhotoDailyItem item : dailyItems) {
				String path = AddressConstant.PHOTO_DAILY_IMAGE_LOCAL.replace(
						"ID", item.getId() + "");
				File file = new File(path);
				if (file.exists()) {
					file.delete();
				}
			}
		}

		// 开始更新
		dailyItems.clear();
		bitmapMap.clear();
		worker = new Worker();
		worker.start();
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setTitle(R.string.photo_daily_list_progress_title);
		progressDialog
				.setMessage(getText(R.string.photo_daily_list_progress_content));
		progressDialog.setButton(
				getText(R.string.photo_daily_list_progress_btn_cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialoginterface, int i) {
						worker.kill();
					}
				});
		progressDialog.show();
		synchronized (worker) {
			worker.notify();
		}
	}

	/**
	 * “返回”按钮事件方法
	 * 
	 * @param v
	 */
	public void onExitClicked(View v) {
		finish();
	}

	/**
	 * “上一页”按钮事件方法
	 * 
	 * @param v
	 */
	public void onPrevClicked(View v) {
		if (page <= 1) {
			return;
		}

		page--;
		onUpdateClicked(v);
	}

	/**
	 * “下一页”按钮事件方法
	 * 
	 * @param v
	 */
	public void onNextClicked(View v) {
		page++;
		onUpdateClicked(v);
	}

	/**
	 * @author lorking0531
	 * 
	 */
	private class ImageListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			if (dailyItems == null) {
				return 0;
			}
			return dailyItems.size();
		}

		@Override
		public Object getItem(int position) {
			return dailyItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			PhotoDailyItem temp = dailyItems.get(position);
			return Long.parseLong(temp.getId());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PhotoDailyItem item = dailyItems.get(position);
			ViewGroup theParent;
			if (convertView == null) {
				LayoutInflater inflater = PhotoDailyList.this
						.getLayoutInflater();
				theParent = (ViewGroup) inflater.inflate(
						R.layout.photo_daily_list_item, parent, false);
			} else {
				theParent = (ViewGroup) convertView;
			}

			LinearLayout layout = (LinearLayout) theParent.getChildAt(1);
			TextView updateView = (TextView) layout.getChildAt(0);
			String update = getString(R.string.photo_daily_list_item_update)
					.replace("REPL", item.getDate());
			updateView.setText(update);
			TextView countView = (TextView) layout.getChildAt(1);
			String count = getString(R.string.photo_daily_list_item_count)
					.replace("REPL", item.getCount());
			countView.setText(count);
			// 显示图片的操作
			ImageView imageView = (ImageView) theParent.getChildAt(0);
			Bitmap bit = bitmapMap.get(String.valueOf(position));
			imageView.setImageBitmap(bit);
			imageView.setMaxWidth((int) (ICON_WIDTH * scaleRatio));
			imageView.setMaxHeight((int) (ICON_HEIGHT * scaleRatio));
			imageView.setMinimumWidth((int) (ICON_WIDTH * scaleRatio));
			imageView.setMinimumHeight((int) (ICON_HEIGHT * scaleRatio));
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			return theParent;
		}
	}

	/**
	 * 网络连接并更新菜单信息的工作者线程
	 * 
	 * @author shawn
	 * 
	 */
	private class Worker extends Thread {
		// 线程是否为意外退出的标记
		private boolean cancel = false;

		/**
		 * 强制杀死工作者线程
		 */
		public void kill() {
			cancel = true;
			this.interrupt();
		}

		@Override
		public void run() {
			try {
				// 等待对话框创建完成
				synchronized (this) {
					wait();
				}

				// 此处访问网络并获取图片分类菜单
				fetchItems(dailyItems);

				// 关闭进度对话框并通知界面更新
				progressDialog.dismiss();
				if (!cancel) {
					// 在非意外中断情况下才更新界面
					Message msg = new Message();
					msg.what = REFRESHED;
					handler.sendMessage(msg);
				} else {
					// 意外中断的情况下，显示错误对话框
					Message msg = new Message();
					msg.what = FAILED;
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				// 清除列表
				try {
					progressDialog.dismiss();
				} catch (Exception ex) {
				}
				;
				dailyItems.clear();
				// 意外中断的情况下，显示错误对话框
				Message msg = new Message();
				msg.what = FAILED;
				handler.sendMessage(msg);
				Log.d(this.getClass().getName(), "", e);
			}
		}

		// 解析种类的列表
		private void fetchItems(List<PhotoDailyItem> dailyItems)
				throws Exception {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			String url = AddressConstant.PHOTO_DAILY.replace("ID", category + "").replace("PAGE", page + "");
			Document doc = db.parse(url);
			NodeList nodeList = doc.getElementsByTagName("daily");
			int len = nodeList.getLength();
			for (int i = 0; i < len; i++) {
				PhotoDailyItem item = new PhotoDailyItem();// 封装的bean
				Node node = nodeList.item(i);
				NodeList nodes = node.getChildNodes();
				int count = nodes.getLength();
				for (int j = 0; j < count; j++) {
					Node pairNode = nodes.item(j);
					String nodeName = pairNode.getNodeName();
					if ("id".equals(nodeName)) {
						String id = pairNode.getTextContent();
						item.setId(id);
					} else if ("date".equals(nodeName)) {
						String date = pairNode.getTextContent();
						item.setDate(date);
					} else if ("count".equals(nodeName)) {
						String imageCount = pairNode.getFirstChild()
								.getNodeValue();
						item.setCount(imageCount);
					}
				}

				// 加载图片并缓存
				saveIcon(item.getId());

				// 加入list
				dailyItems.add(item);
			}
		}

		private void saveIcon(String id) throws Exception {
			String path = AddressConstant.PHOTO_DAILY_IMAGE_LOCAL.replace("ID",
					id);
			File file = new File(path);
			if (!file.exists()) {
				String url = AddressConstant.PHOTO_DAILY_IMAGE.replace("ID", id);
				URL imgUrl = new URL(url);
				InputStream is = imgUrl.openStream();
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				is.close();

				File dir = file.getParentFile();
				if (!dir.exists()) {
					dir.mkdirs();
				}

				if (file.exists()) {
					file.delete();
				}

				file.createNewFile();
				FileOutputStream os = new FileOutputStream(file);
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
				os.close();
			}
		}
	}

//	// 读取图片
//	private void fetchImage(PhotoDailyItem[] itemArray, int index) {
//		PhotoDailyUpdateThread thread = new PhotoDailyUpdateThread();
//		thread.fetchImage(itemArray, index);
//	}

	/**
	 * 更新图片的id
	 * 
	 * @author lorking0531
	 * 
	 */
	private class PhotoDailyUpdateThread implements Runnable {
		// 读取图片
		@Override
		public void run() {
			processPic();
		}

		// 处理图片的加载
		public void processPic() {
			int count = 0;
			for (PhotoDailyItem item : dailyItems) {
				String path = AddressConstant.PHOTO_DAILY_IMAGE_LOCAL.replace(
						"ID", item.getId());
				Bitmap bitmap = readPicFrom(path);
				item.setLoadStatus(PhotoDailyItem.STATUS_LOADED);
				Message msg = new Message();
				synchronized (bitmapMap) {
					bitmapMap.put(String.valueOf(count), bitmap);
				}
				// 发送消息
				Bundle data = new Bundle();
				data.putInt("key", count);
				drawImageHandler.sendMessage(msg);
				count++;
			}
		}

		// 读取图片
		private Bitmap readPicFrom(String path) {
			InputStream is = null;
			try {
				File file = new File(path);
				is = new FileInputStream(file);
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				return bitmap;
			} catch (Exception e) {
				return null;
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (Exception e) {
					}
					;
				}
			}
		}
	}
}
